﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.DirectoryServices;
using System.Linq;
using System.Text;
using System.Data;
using SpringStudio.Common;
using SpringStudio.DAL;

namespace Sdepci.InfoCode.BLL.Authority
{
    /// <summary>
    /// 用户管理器类
    /// </summary>
    public class UserManager
    {
        /// <summary>
        /// 域用户验证
        /// </summary>
        /// <param name="userId">用户工号（域用户名）</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        public bool IsAuthenticated(string username, string password)
        {
            DirectoryEntry entry = new DirectoryEntry("LDAP://sdepci", @"sdepci\" + username, password);

            try
            {
                DirectorySearcher search = new DirectorySearcher(entry);

                search.Filter = "(SAMAccountName=" + username + ")";
                search.PropertiesToLoad.Add("cn");
                SearchResult result = search.FindOne();

                if (result != null)
                {
                    return true;
                }
            }
            catch (Exception ex)
            {
                ExceptionHandler.Handle(ex);
            }

            return false;
        }

        /// <summary>
        /// 从AD域中同步用户资料
        /// </summary>
        /// <returns>是否成功</returns>
        public bool Synchronize()
        {
            try
            {
                DirectoryEntry entry = new DirectoryEntry("LDAP://sdepci", @"sdepci\u8888", "sdepci");
                DirectorySearcher searcher = new DirectorySearcher(entry);
                searcher.Filter = "(&(objectCategory=person)(objectClass=user))";
                searcher.PropertiesToLoad.Clear();
                SearchResultCollection searchResultCollection = searcher.FindAll();

                foreach (SearchResult result in searchResultCollection)
                {
                    string userId = string.Empty;
                    string UserName = string.Empty;
                    string department = string.Empty;

                    if (result.Properties.Contains("samaccountname"))
                    {
                        ResultPropertyValueCollection resultValue = result.Properties["samaccountname"];
                        if (resultValue != null && resultValue.Count > 0 && resultValue[0] != null)
                        {
                            userId = resultValue[0].ToString();
                        }
                    }

                    if (result.Properties.Contains("displayname"))
                    {
                        ResultPropertyValueCollection resultValue = result.Properties["displayname"];
                        if (resultValue != null && resultValue.Count > 0 && resultValue[0] != null)
                        {
                            UserName = resultValue[0].ToString();
                        }
                    }

                    if (result.Properties.Contains("department"))
                    {
                        ResultPropertyValueCollection resultValue = result.Properties["department"];
                        if (resultValue != null && resultValue.Count > 0 && resultValue[0] != null)
                        {
                            department = resultValue[0].ToString();
                        }
                    }

                    if (userId.Length > 0 && userId.ToLower().IndexOf("u") == 0)
                    {
                        this.Add(userId, UserName, department);  // 将用户信息添加到数据库
                    }
                }

                return true;
            }
            catch (Exception ex)
            {
                ExceptionHandler.Handle(ex);
                return false;
            }
        }

        /// <summary>
        /// 增加
        /// </summary>
        /// <param name="userId">用户证档号</param>
        /// <param name="userName">用户姓名</param>
        /// <param name="deptInfo">部门信息</param>
        /// <returns>是否成功</returns>
        public bool Add(string userId, string userName, string deptInfo)
        {
            try
            {
                string sql = string.Empty;
                
                // 首先判断是否已有该用户信息
                sql = "Select UserId From InfoCodeUsers Where UserId=@UserId";
                DataSet ds = SqlHelper.ExecuteDataSet(ConnectionString.Default, CommandType.Text, sql,
                    SqlHelper.NewSqlParameter("@UserId", userId));
                if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    sql = "Update InfoCodeUsers Set UserName=@UserName,DeptInfo=@DeptInfo Where UserId=@UserId";
                    SqlHelper.ExecuteNonQuery(ConnectionString.Default, CommandType.Text, sql,
                        SqlHelper.NewSqlParameter("@UserId", userId),
                        SqlHelper.NewSqlParameter("@UserName", userName),
                        SqlHelper.NewSqlParameter("@DeptInfo", deptInfo));

                    return false;
                }
                else
                {
                    sql = "Insert Into InfoCodeUsers (UserId,UserName,DeptInfo) Values(@UserId,@UserName,@DeptInfo)";
                    SqlHelper.ExecuteNonQuery(ConnectionString.Default, CommandType.Text, sql,
                        SqlHelper.NewSqlParameter("@UserId", userId),
                        SqlHelper.NewSqlParameter("@UserName", userName),
                        SqlHelper.NewSqlParameter("@DeptInfo", deptInfo));

                    return true;
                }
            }
            catch (Exception ex)
            {
                ExceptionHandler.Handle(ex);
                return false;
            }
        }

        /// <summary>
        /// 验证用户是否存在
        /// </summary>
        /// <param name="userId">用户证档号</param>
        /// <returns></returns>
        public bool Exist(string userId)
        {
            try
            {
                string sql = "Select UserId From InfoCodeUsers Where UserId=@UserId";
                DataSet ds = SqlHelper.ExecuteDataSet(ConnectionString.Default, CommandType.Text, sql,
                    SqlHelper.NewSqlParameter("@UserId", userId));
                if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                ExceptionHandler.Handle(ex);
                return false;
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="userId">用户证档号</param>
        /// <returns>是否成功</returns>
        public bool Delete(string userId)
        {
            try
            {
                string sql = string.Empty;
                sql = "Delete From InfoCodeUsers Where UserId=@UserId";
                SqlHelper.ExecuteNonQuery(ConnectionString.Default, CommandType.Text, sql,
                    SqlHelper.NewSqlParameter("@UserId", userId));

                return true;
            }
            catch (Exception ex)
            {
                ExceptionHandler.Handle(ex);
                return false;
            }
        }

        /// <summary>
        /// 修改用户角色
        /// </summary>
        /// <param name="userId">用户证档号</param>
        /// <param name="roleGuid">角色Guid</param>
        /// <returns></returns>
        public bool ModifyRole(string userId, string roleGuid)
        {
            try
            {
                string sql = string.Empty;
                sql = "Update InfoCodeUsers Set RoleGuid=@RoleGuid Where UserId=@UserId";
                SqlHelper.ExecuteNonQuery(ConnectionString.Default, CommandType.Text, sql,
                    SqlHelper.NewSqlParameter("@UserId", userId),
                    SqlHelper.NewSqlParameter("@RoleGuid", roleGuid));

                return true;
            }
            catch (Exception ex)
            {
                ExceptionHandler.Handle(ex);
                return false;
            }
        }
    }
}
